using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;

namespace DOTS.DOD.LESSON6
{
    [BurstCompile]
    [RequireMatchingQueriesForUpdate]
    [UpdateInGroup(typeof(MoveCubesWithWayPointsSystemGroup))]
    //[UpdateAfter(typeof(MoveCubesWithWayPointsSystem))]
    public partial struct InputSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<WayPoint>();
        }

        //[BurstCompile] //使用了托管对象时不可开启Burst编译
        public void OnUpdate(ref SystemState state)
        {
            if (Input.GetMouseButtonDown(0))
            {
                DynamicBuffer<WayPoint> path = SystemAPI.GetSingletonBuffer<WayPoint>();
                var worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                float3 wayPoint = new float3(worldPos.x, worldPos.y, 0);
                if (path.Length > 0)
                {
                    float minDis = float.MaxValue;
                    int index = 0;
                    for (int i = 0; i < path.Length; i++)
                    {
                        float dis = math.distance(path[i].Point, wayPoint);
                        if (dis < minDis)
                        {
                            minDis = dis;
                            index = i;
                        }
                    }

                    path.Insert(index, new WayPoint()
                    {
                        Point = wayPoint,
                    });
                }
            }
        }
    }
}